package com.example.myandroidtest.ui.component.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myandroidtest.databinding.ActivityBroadcastBinding;

public class BroadcastActivity extends AppCompatActivity {

    private static final String CUSTOM_ACTION = "CUSTOM_ACTION";
    ActivityBroadcastBinding binding;
    //进程之间的通信
    MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBroadcastBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        register();
    }

    void register() {
        receiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CUSTOM_ACTION);
        registerReceiver(receiver, intentFilter, Context.RECEIVER_NOT_EXPORTED);
    }

    private void initView() {
        binding.btnSend.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setAction(CUSTOM_ACTION);
            System.out.println("包名" + getPackageName());
            intent.setPackage(getPackageName());
            intent.putExtra("data", "发送广播的数据");
            sendBroadcast(intent);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("收到广播");
            if (intent != null) {
                String data = intent.getStringExtra("data");
                Toast.makeText(context, "收到广播" + data, Toast.LENGTH_SHORT);
            }

        }
    }
}